package com.cqw.es.service;

import com.cqw.es.domain.EsEntity;
import com.cqw.es.mapper.EsMapper;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-20 14:44
 * @Description:
 */
@Service
public class EsService {


    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private EsMapper esMapper;


    public List<EsEntity> query() {
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withQuery(matchAllQueryBuilder);

        SearchHits<EsEntity> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), EsEntity.class);

        //组装对象
        List<EsEntity> esEntities = new ArrayList<>();
        searchHits.forEach(hit -> {
            EsEntity esEntity = hit.getContent();
            esEntities.add(esEntity);
        });
        return esEntities;
    }


}
